"use client";
import { Edit, useForm } from "@refinedev/antd";
import { useParsed } from "@refinedev/core";
import {Form, Input, InputNumber, TreeSelect, Descriptions, Tabs, Radio, Row, Col, Spin} from "antd";
import { useEffect, useState } from "react";
import { getCategoryTree, selectCategoryDescs } from "../../../../../common/api/category_action";

function buildTree(list: any[]) {
  const map: Record<number, any> = {};
  const roots: any[] = [];
  list.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });
  list.forEach(item => {
    if (item.fid && map[item.fid]) {
      map[item.fid].children.push(map[item.id]);
    } else {
      roots.push(map[item.id]);
    }
  });
  return [{id:0,alias:'根分类',children:roots}];
}

export default function CategoryEdit() {
  const { id } = useParsed();
  const { formProps, saveButtonProps ,formLoading } = useForm({
    resource: "project/category",
    id: id
  });
  const [treeData, setTreeData] = useState<any[]>([]);
  const [availableLangs, setAvailableLangs] = useState<string[]>(['zh-CN', 'zh-TW', 'en-US']);
  
  useEffect(() => {
    getCategoryTree().then((res: any) => {
      if (res.code == 200) {
        setTreeData(buildTree(res.data.list));
      }
    });
  }, []);
  useEffect(() => {
    if (formProps?.initialValues?.alias) {
      // 获取分类描述
      selectCategoryDescs(formProps.initialValues.alias).then((res: any) => {
        if (res.data && res.data.length > 0) {
          formProps?.form?.setFieldsValue({
            descs: res.data
          });
        } else {
          formProps?.form?.setFieldsValue({
            descs: [
              { id: undefined, lang: 'zh-CN', title: '', keyword: '', description: '' },
              { id: undefined, lang: 'zh-TW', title: '', keyword: '', description: '' },
              { id: undefined, lang: 'en-US', title: '', keyword: '', description: '' },
            ]
          });
        }
      });
    }
  }, [formProps?.initialValues?.alias]);
  return (
    <Edit saveButtonProps={saveButtonProps} isLoading={formLoading}>
      <Form {...formProps} layout="horizontal" labelCol={{ span: 3 }}>
        <Form.Item name={["alias"]} label="别名" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name={["fid"]} label="父级分类">
          <TreeSelect
              treeData={treeData}
              fieldNames={{ label: 'alias', value: 'id', children: 'children' }}
              allowClear
              placeholder="请选择父级分类"
              treeDefaultExpandAll
          />
        </Form.Item>
        <Row>
          <Col span={12}>
            <Form.Item name={["sort"]} label="排序">
              <InputNumber style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name={["status"]} label="状态">
              <Radio.Group options={[{label:'启用',value:1},{label:'禁用',value:0}]} />
            </Form.Item>
          </Col>
        </Row>

        <Form.List name={["descs"]}>
          {(fields:any[]) => {
            // 将 fields 转为 map，方便按 lang 查找
            const fieldMap = new Map(fields.map(f => {
              const fieldLang = formProps.form?.getFieldValue(['descs', f.name, 'lang']);
              return [fieldLang, f];
            }));

            return (
                <Tabs defaultActiveKey="zh-CN" style={{ marginTop: 24 }}>
                  {availableLangs.map(lang => {
                    const field = fieldMap.get(lang);
                    const fieldIndex = fields.findIndex(f =>
                        formProps.form?.getFieldValue(['descs', f.name, 'lang']) === lang
                    );

                    // 如果该语言没有对应字段，自动添加（比如初始化时）
                    if (fieldIndex === -1) {
                      // 可以在这里自动 push 一个新项，但更推荐在 useEffect 中初始化
                      return null;
                    }

                    const f = fields[fieldIndex];

                    return (
                        <Tabs.TabPane tab={lang} key={lang}>
                          {/* 隐藏的 lang 字段 */}
                          <Form.Item name={[f.name, 'lang']} hidden initialValue={lang} />

                          <Form.Item
                              name={[f.name, 'title']}
                              label="标题"
                              rules={[{ required: true, message: `${lang} 标题必填` }]}
                          >
                            <Input />
                          </Form.Item>
                          <Form.Item
                              name={[f.name, 'keyword']}
                              label="关键词"
                              rules={[{ required: true, message: `${lang} 关键词必填` }]}
                          >
                            <Input />
                          </Form.Item>
                          <Form.Item
                              name={[f.name, 'description']}
                              label="描述"
                              rules={[{ required: true, message: `${lang} 描述必填` }]}
                          >
                            <Input />
                          </Form.Item>
                        </Tabs.TabPane>
                    );
                  })}
                </Tabs>
            )
          }}
        </Form.List>
      </Form>
    </Edit>
  );
} 